/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-28 13:39:23   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.OffsetDateTime;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.Shift;
import com.zx.cloud.common.token.PasswordHashUtil;
import com.zx.cloud.controller.StatusCode;
import com.zx.cloud.domain.Client;
import com.zx.cloud.domain.ClientAuth;
import com.zx.cloud.domain.ClientBankCard;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.IdCardImg;
import com.zx.cloud.domain.VerifyMsg;
import com.zx.cloud.persistence.ClientAuthMapper;
import com.zx.cloud.persistence.ClientBankCardMapper;
import com.zx.cloud.persistence.ClientInfoMapper;
import com.zx.cloud.persistence.ClientMapper;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;

@Transactional
@Service
public class ClientService extends CrudServiceImpl<Client>{
	 private static final Logger LOGGER = LoggerFactory.getLogger(ClientService.class);
    @Autowired
	private ClientAuthService clientAuthService;
    @Autowired
    private ClientInfoService clientInfoService;
    @Autowired
    private ClientBankCardService clientBankCardService;
    @Autowired
    private VerifyMsgService verifyMsgService;
	@Autowired
	private DictMapper dictMapper;
    
    @Autowired
    private ClientInfoMapper clientInfoMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ClientAuthMapper clientAuthMapper;
    @Autowired
    private ClientBankCardMapper  clientBankCardMapper;
	
    private  static  final  Object obj = new Object();
	
  	@Autowired
    public ClientService(CrudMapper<Client> mapper) {
        super(mapper);
    }

  	public long handleRegisterClient(Client client){
  		String loginName = client.getLoginName();
  		Thread  chileThread=new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (LOGGER) {
					if(StringUtils.isNotEmpty(loginName)){
						if(null != clientMapper.findLoginNameExist(loginName)){
					 	  System.out.println("********************************"+loginName+"用户已经存在, 请尝试登录***************************");
						}else{
							String loginPwd = client.getLoginPwd();
							if(StringUtils.isNotEmpty(loginPwd)){
								try {
									//给用户密码加密
									client.setLoginPwd(PasswordHashUtil.createHash(loginPwd));
								} catch (NoSuchAlgorithmException e) {
									e.printStackTrace();
								} catch (InvalidKeySpecException e) {
									e.printStackTrace();
								}
							}
							client.setCreateTime(OffsetDateTime.now());
							/**注册渠道*/
							 String  channel_code=client.getChannelCode();
						
							 Dict dict=new Dict();
		        			 dict.setParentCode("CC0001");
		        			 List<Dict> dicts=dictMapper.getDitByParentCode(dict);
		        			if(StringUtils.isNotEmpty(channel_code)){
		        				 for (int i = 0; i < dicts.size(); i++) {
			        				 String  code=dicts.get(i).getCode();
				        				if(code.equals(channel_code)  ){
				        					client.setChannelName(dicts.get(i).getName());
				        					client.setChannelUrl(dicts.get(i).getValue());
				        					
				        					client.setRegistType("web");
				        				}
			        			}
		        			} else{
		        				 for (int i = 0; i < dicts.size(); i++) {
			        				 String  code=dicts.get(i).getCode();
				        				if(code.equals("CC99999")  ){
				        					client.setChannelName(dicts.get(i).getName());
				        					client.setChannelUrl(dicts.get(i).getValue());
				        					client.setChannelCode("CC99999");
				        				}
			        			}
		        			}
		        			
				  		//保存
				  		clientMapper.insert(client);
				  	   //创建会员认证信息表
				  		ClientAuth clientAuth = new ClientAuth();
				  		clientAuth.setClientId(client.getId());
				  		//保存入会员认证信息
				  		clientAuthMapper.insert(clientAuth);
				  		//创建会员详细信息表
				  		ClientInfo clientInfo = new ClientInfo();
				  		clientInfo.setClientId(client.getId());
				  		clientInfo.setPhone(loginName);
				  		clientInfo.setCreateTime(OffsetDateTime.now());
				  		//保存入会员详细信息
				  		clientInfoMapper.insert(clientInfo);
				  		//创建会员银行卡信息表
				  		ClientBankCard clientBankCard = new ClientBankCard();
				  		clientBankCard.setClientId(client.getId());
				  		//保存入会员银行卡信息
				  		clientBankCardMapper.insert(clientBankCard);
			                      }
		                      }
						}
					}
					
	            });
  		     chileThread.start();
  		     try {
//				chileThread.join();
  		    	 Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		  	 return client.getId();
  	} 	
  	
  	public long handleLoginClient(Client client){
  		
  		String insLoginPwd = null;
  		
  		Client insClient = null;
  		
  		String loginName = client.getLoginName();
  		if(StringUtils.isNotEmpty(loginName)){
  			insClient = clientMapper.findLoginNameExist(loginName);
  			if(null != insClient){
  				insLoginPwd = insClient.getLoginPwd();
  			}else{
  				Shift.fatal(StatusCode.USER_NOT_EXISTS, "用户不存在, 请先注册");
  			}
  		}
  		
  		String loginPwd = client.getLoginPwd();
  		if(StringUtils.isNotEmpty(loginPwd)){
  			try {
				if(!PasswordHashUtil.validatePassword(loginPwd, insLoginPwd)){
					Shift.fatal(StatusCode.INVALID_CREDENTIAL, "用户名或密码错误");
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
  		}
  		
  		return insClient.getId();
  	}
  	
  	public int handleForgotPassword(Client client){
  		
  		int resultInt = 0;
  		
  		Client insClient = clientMapper.findLoginNameExist(client.getLoginName());
		if(null != insClient){
			try {
				insClient.setLoginPwd(PasswordHashUtil.createHash(client.getLoginPwd()));
				super.update(insClient);
				resultInt = 1;
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
		}else{
			Shift.fatal(StatusCode.USER_NOT_EXISTS, "用户不存在, 请先注册");
		}
  		
  		return resultInt;
  	}
  	
  	public int handleModifyPassword(Client client){
  		
  		int resultInt = 0; //操作结果状态 1：修改成功
  		
  		Client insClient = clientMapper.get(client.getId());
		try {
			if (!PasswordHashUtil.validatePassword(client.getOldLoginPwd(), insClient.getLoginPwd())) {
				Shift.fatal(StatusCode.OLD_PASSWORD_ERROR, "原密码输入错误");
			} else {
				insClient.setLoginPwd(PasswordHashUtil.createHash(client.getLoginPwd()));
				super.update(insClient);
				resultInt = 1;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
  		
  		return resultInt;
  	}
  	
  	public ClientAuth SelectClientAuth(Client client){
  		
  		ClientAuth result = clientAuthMapper.findByClientID(client.getId());
  		
  		return result;
  		
  	}
  	/**
  	 * @Description:身份证扫描认证
  	 */
  	public int handleClientIDCardMsg(Long userId, VerifyMsg verifyMsg){
  		LOGGER.info("*******************************身份证扫描认证*******************************");
  		verifyMsg.setCreateDate(OffsetDateTime.now());
  		verifyMsg.setClientId(userId);
  		verifyMsgService.insert(verifyMsg); //保存用户身份证扫描信息
  		
  		if(null != userId){
  			ClientInfo clientInfo = clientInfoMapper.findClientById(userId);
  	  		if(null != clientInfo){
  	  	  		clientInfo.setRealName(verifyMsg.getName());
  	  	  		clientInfo.setSex(verifyMsg.getSex());
  	  	  		clientInfo.setIdNo(verifyMsg.getIdnum());
  	  	  		clientInfo.setIdAddr(verifyMsg.getAddress());
  	  	  		clientInfo.setNational(verifyMsg.getNation());
  	  	  		clientInfo.setFrontImg(verifyMsg.getTheFrontOfIDCard());
  	  	  		clientInfo.setBackImg(verifyMsg.getTheReverseOfIDCard());
  	  	  		clientInfo.setUpdateTime(OffsetDateTime.now());
  	  	  		
  	  	  		int year = Integer.parseInt(verifyMsg.getYear());
  	  	  		int month = Integer.parseInt(verifyMsg.getMonth());
  	  	  		int day = Integer.parseInt(verifyMsg.getDay());
  	  	  		
  	  	  		OffsetDateTime nowDate = OffsetDateTime.now();
  	  	  		int insYear = nowDate.getYear();
  	  	  		int insMonth = nowDate.getMonthValue();
  	  	  		int insDay = nowDate.getDayOfMonth();
  	  	  		
  	  	  		int yearMinus = insYear - year;
  	  	  		int monthMinus = insMonth - month;
  	  	  		int dayMinus = insDay - day;
  	  	  		
  	  	  		int age = insYear - year;
  	  	  		if (yearMinus < 0) { 
  	  	            age = 0;  
  	  	        } else if (yearMinus == 0) { 
  	  	            if (monthMinus < 0) {
  	  	                age = 0;  
  	  	            } else if (monthMinus == 0) { 
  	  	                if (dayMinus < 0) {
  	  	                    age = 0;  
  	  	                } else if (dayMinus >= 0) {  
  	  	                    age = 1;  
  	  	                }  
  	  	            } else if (monthMinus > 0) {  
  	  	                age = 1;  
  	  	            }  
  	  	        } else if (yearMinus > 0) {  
  	  	            if (monthMinus < 0) {
  	  	            } else if (monthMinus == 0) { 
  	  	                if (dayMinus < 0) {  
  	  	                } else if (dayMinus >= 0) {  
  	  	                    age = age + 1;  
  	  	                }  
  	  	            } else if (monthMinus > 0) {  
  	  	                age = age + 1;  
  	  	            }  
  	  	        }
  	  	  		clientInfo.setAge(age);
  	  	  		/**身份认证：保存会员详细信息的身份认证*/
  	  	  		clientInfoService.update(clientInfo); 
  	  		}
  	    	/**身份认证：标记已经身份认证+判断是否全部认证*/
  	  		ClientAuth clientAuth = clientAuthMapper.findByClientID(userId);
	  		clientAuth.setIdState(1);
	  		clientAuth.setIdTime(OffsetDateTime.now());
	  		if(clientAuth.getContactState() == 1 && clientAuth.getBankCardState() == 1 && 
	  				clientAuth.getPrivateMsg() == 1 && (clientAuth.getJobState() == 1 || clientAuth.getSchoolState() == 1)){
	  			clientAuth.setFlag(1);
	  		}
	  		clientAuthService.update(clientAuth); //保存会员认证信息修改-身份信息验证
  		}
  		
  		return 1;
  	}

	public int saveIDCardImg(IdCardImg idCardImg) {
		Long userId = idCardImg.getClientId();
		if (null != userId) {
			ClientInfo clientInfo = clientInfoMapper.findClientById(userId);
			if (null != clientInfo) {
               ClientInfo newClientInfo=new ClientInfo();
               newClientInfo.setId(clientInfo.getId());
               if(1==idCardImg.getImgType()){
            	   newClientInfo.setFrontImg(idCardImg.getImgUrl());
               }
               if(2==idCardImg.getImgType()){
            	   newClientInfo.setBackImg(idCardImg.getImgUrl());
               }
               clientInfoService.update(newClientInfo);
			}
		}
		return 1;
	}
}
